package com.thoughtworks.biblioteca;

import java.sql.*;

//Understands the auto-generation of a new library number(username) for the user
public class UserNameGenerator {
	Connection connectionToBibliotecaDatabase = null;

	public UserNameGenerator() {
		connectionToBibliotecaDatabase=MySQLConnection.obtainConnection();
	}

	public String generate() {
		try {
			String lastUserName = getLastUserName();
			int newUserNameAsInt = generateNewUserName(lastUserName);
			StringBuffer newUserName = convertToHyphenFormat(newUserNameAsInt);
			String newUserNameFinal = newUserName.toString();
			return newUserNameFinal;

		} catch (Exception e) {
		}
		return null;

	}

	private String getLastUserName() throws SQLException {
		Statement selectUserName = connectionToBibliotecaDatabase.createStatement();
		ResultSet userNamesRecordSet = selectUserName.executeQuery("SELECT username FROM users");
		userNamesRecordSet.last();
		return userNamesRecordSet.getString("username");
		
	}

	private StringBuffer convertToHyphenFormat(int newUserNameAsInt) {
		StringBuffer newUserName = new StringBuffer(Integer
				.toString(newUserNameAsInt));
		newUserName.insert(3, "-");
		return newUserName;
	}

	private int generateNewUserName(String lastUserName) {
		String lastUserNameWithoutHyphen = lastUserName.replace("-", "");
		int lastUserNameAsInt = Integer.parseInt(lastUserNameWithoutHyphen);
		int newUserNameAsInt = lastUserNameAsInt + 1;
		return newUserNameAsInt;
	}

}
